const express = require('express');
// 引入模型对象
const Users = require('../models/users');
const router = new express.Router();
const user_name_reg = /^[A-Za-z][A-Za-z0-9_]{2,19}$/
const password_reg = /^[A-Za-z0-9_]{4,15}$/
router.post('/register',async(req,res)=>{
    console.log(req.body);
    const {user_name,password} = req.body;
    
    // console.log(user_name_reg.test(user_name));
    if(user_name_reg.test(user_name)&&password_reg.test(password)){
       
        try{
            await Users.create(req.body);
            res.send('注册成功！！')
        }catch(e){
            console.log(e);
            res.send('网络延迟，请重新注册！！')
        }
    }else{
        res.send('用户名和密码不符合规则，请求重新注册！！');
    }
})
// 登录
router.post('/login',async(req,res)=>{
    const {user_name,password} = req.body;
    if(user_name_reg.test(user_name) && password_reg.test(password)){
        try{
            const user =await Users.findOne({user_name});
            if(user){
                if(user.password == password){
                    res.send('登录成功！！');
                }else{
                    res.send('密码错误！！')
                }
            }else{
                res.send('该用户不存在，请注册！！')
            }
        }catch(e){
            console.log(e);
            res.send('网络延迟！！')
        }
    }else{
        res.send('用户名和密码不符合规则！！')
    }
})

module.exports = router;